package service

import (
	"encoding/json"
	"fmt"
	"math/rand"
	"rongyy/src/helper"
	"rongyy/src/middlewares"
	"rongyy/src/models"
	"strconv"
	"time"
)

type WxNoticeService struct {
}

// 挂号成功通知
func (ps *WxNoticeService) RegSuccessNotice(req *models.ReqNoticeParams) error {
	bi := &models.BusinessInfo{
		PatName:         req.PatName,
		DocName:         req.DocName,
		PatHospitalId:   req.PatHospitalId,
		DepartmentName:  req.DepartmentName,
		AppointmentTime: req.AppointmentTime,
		Memo:            req.Memo,
		RedirectPage: models.RedirectPage{
			PageType: "mini_program",
			AppId:    "wxd5cd38899ac167af",
			Fullpath: "/pages/registered/myRegister?current=1",
		},
	}
	req.OpenId = req.OpenId
	req.OrderId = req.PatHospitalId + time.Now().String()
	err := ps.SendNotice(req, 1501001, bi, "挂号成功通知")
	if err != nil {
		middlewares.Logger.Println("挂号成功通知 error==== ", err)
		//return err
	}
	return nil
}

func (ps *WxNoticeService) SendNotice1(req *models.ReqNoticeParams) error {
	token, err := (&WxConfService{}).GetGzhToken()
	if err != nil {
		return err
	}
	if token != "" {
		bi := &models.BusinessInfo{
			PatName:         req.PatName,
			DocName:         req.DocName,
			PatHospitalId:   req.PatHospitalId,
			DepartmentName:  req.DepartmentName,
			AppointmentTime: req.AppointmentTime,
			RedirectPage: models.RedirectPage{
				PageType: "mini_program",
				AppId:    "wxd5cd38899ac167af",
				Fullpath: req.FullPath,
			},
		}
		rand.Seed(time.Now().UnixNano())
		t := rand.Intn(10000)
		ts := strconv.FormatInt(time.Now().UnixMicro(), 10)
		msgId := "msg" + ts + strconv.Itoa(t)
		req := &models.ReqWxNotice{
			Status:       1501001,
			OpenId:       req.OpenId,
			OrderId:      req.OrderId,
			AppId:        "wx20a0569be221aa8c",
			MsgId:        msgId,
			BusinessId:   150,
			BusinessInfo: *bi,
		}

		res, err := helper.PostJson("https://api.weixin.qq.com/cityservice/sendchannelmsg?access_token="+token, req)
		middlewares.Logger.Println(string(res))
		middlewares.Logger.Println(err)
		if err != nil {
			return err
		}
		return nil
	}
	return fmt.Errorf("token为空，请更新")
}

// 停诊通知
func (ps *WxNoticeService) Suspend(req *models.ReqNoticeParams) error {
	data, total, err := (&models.RegisterModel{}).QueryByScheduleItemCode(req.ScheduleItemCode)
	if total == 0 {
		return fmt.Errorf("没有相应挂号患者")
	}
	for _, item := range data {
		bi := &models.BusinessInfo{
			HosptialName:    "成都公卫中心",
			DocName:         item.DoctorName,
			DepartmentName:  item.DeptName,
			AppointmentTime: item.AdmitRange,
			StopTime:        item.AdmitRange,
			RedirectPage: models.RedirectPage{
				PageType: "mini_program",
				AppId:    "wxd5cd38899ac167af",
				Fullpath: "/pages/registered/myRegister?current=1",
			},
		}
		req.OpenId = item.Openid
		req.OrderId = item.ScheduleItemCode
		err := ps.SendNotice(req, 1501010, bi, "停诊通知")
		if err != nil {
			middlewares.Logger.Println("停诊通知 error==== ", err)
			return err
		}
	}
	return err
}

// 取消挂号成功通知
func (ps *WxNoticeService) CancelRegNotice(req *models.ReqNoticeParams) error {
	bi := &models.BusinessInfo{
		PatName:         req.PatName,
		DocName:         req.DocName,
		PatHospitalId:   req.PatHospitalId,
		DepartmentName:  req.DepartmentName,
		AppointmentTime: req.AppointmentTime,
		RedirectPage: models.RedirectPage{
			PageType: "mini_program",
			AppId:    "wxd5cd38899ac167af",
			Fullpath: "/pages/index/index?navTitle=toPaid",
		},
	}
	req.OpenId = req.OpenId
	req.OrderId = req.PatHospitalId + time.Now().String()
	err := ps.SendNotice(req, 1501004, bi, "取消挂号成功通知")
	if err != nil {
		middlewares.Logger.Println("取消挂号成功通知 error==== ", err)
		//return err
	}
	return err
}

// 病案通知
func (ps *WxNoticeService) CaseNotice(req *models.ReqNoticeParams) error {
	middlewares.Logger.Println("病案复印通知 req==== ", req)
	bi := &models.BusinessInfo{
		PatName:       req.PatName,
		ApplyStatus:   req.ApplyStatus,
		AuditStatus:   req.AuditStatus,
		ReceiveWay:    "邮寄",
		PatHospitalId: "",
		Memo:          req.Memo,
		RedirectPage: models.RedirectPage{
			PageType: "mini_program",
			AppId:    "wxd5cd38899ac167af",
			Fullpath: "/pages/medicalRecord/detail?id=" + fmt.Sprintf("%d", req.Id),
		},
	}
	req.OpenId = req.OpenId
	req.OrderId = req.PatHospitalId + time.Now().String()
	err := ps.SendNotice(req, 1502021, bi, "病案复印通知")
	if err != nil {
		middlewares.Logger.Println("病案复印通知 error==== ", err)
		//return err
	}
	return err
}

func (ps *WxNoticeService) SendNoticeOpUnpaid(req *models.ReqNoticeParams) error {
	middlewares.Logger.Println("门诊待缴费订单提醒 req==== ", req)
	middlewares.Logger.Println("门诊待缴费订单提醒 req==== ", "/pages/outpatientPayment/unpaidRecipe?patientId="+req.PatId+"&adm="+req.Adm)

	bi := &models.BusinessInfo{
		PatName:        req.PatName,
		PatHospitalId:  req.PatId,
		DepartmentName: req.DepartmentName,
		PayAmount:      req.PayAmount,
		Memo:           req.Memo,
		RedirectPage: models.RedirectPage{
			PageType: "mini_program",
			AppId:    "wxd5cd38899ac167af",
			Fullpath: "/pages/outpatientPayment/unpaidRecipe?patientId=" + req.PatId + "&adm=" + req.Adm,
		},
	}
	// 查找openid
	data, err := (&models.CardModel{}).FindOpenidBySourceId(req.PatId)
	if err != nil {
		middlewares.Logger.Println("门诊待缴费订单提醒 error==== ", err)
		//return err
	}
	middlewares.Logger.Println("门诊待缴费订单提醒 data==== ", data)
	for _, item := range data {
		req.OpenId = item.MpOpenid
		req.OrderId = req.PatHospitalId + time.Now().String()
		err := ps.SendNotice(req, 1501018, bi, "门诊待缴费订单提醒")
		if err != nil {
			middlewares.Logger.Println("门诊待缴费订单提醒 error==== ", err)
			//return err
		}
	}

	return err
}

// 公共方法
func (ps *WxNoticeService) SendNotice(req *models.ReqNoticeParams, StatusCode int, bi *models.BusinessInfo, name string) error {
	token, err := (&WxConfService{}).GetGzhToken()
	if err != nil {
		return err
	}
	fmt.Println(token)
	if token != "" {
		rand.Seed(time.Now().UnixNano())
		t := rand.Intn(10000)
		ts := strconv.FormatInt(time.Now().UnixMicro(), 10)
		msgId := "msg" + ts + strconv.Itoa(t)
		req := &models.ReqWxNotice{
			Status:       StatusCode,
			OpenId:       req.OpenId,
			OrderId:      req.OrderId,
			AppId:        "wx20a0569be221aa8c",
			MsgId:        msgId,
			BusinessId:   150,
			BusinessInfo: *bi,
		}

		res, err := helper.PostJson("https://api.weixin.qq.com/cityservice/sendchannelmsg?access_token="+token, req)
		jy := &models.JyMsgModel{
			PatientId: bi.PatHospitalId,
			Openid:    req.OpenId,
			OrderId:   req.OrderId,
			Type:      name,
			Result:    "发送成功",
		}

		middlewares.Logger.Println(string(res))

		resp := &models.JyRespModel{}

		err = json.Unmarshal(res, resp)
		middlewares.Logger.Println(resp)
		if err != nil {
			middlewares.Logger.Println(err)
			return err
			jy.Result = err.Error()
		}
		jy.Insert()
		return nil
	}
	return fmt.Errorf("token为空，请更新")
}

//
//func (ps *WxNoticeService) SendNotice(req *models.ReqNoticeParams, StatusCode int, bi *models.BusinessInfo) error {
//	token, err := (&WxConfService{}).GetGzhToken()
//	if err != nil {
//		return err
//	}
//	if token != "" {
//		//bi := &models.BusinessInfo{
//		//	PatName:         req.PatName,
//		//	DocName:         req.DocName,
//		//	PatHospitalId:   req.PatHospitalId,
//		//	DepartmentName:  req.DepartmentName,
//		//	AppointmentTime: req.AppointmentTime,
//		//	RedirectPage: models.RedirectPage{
//		//		PageType: "mini_program",
//		//		AppId:    "wxd5cd38899ac167af",
//		//		Fullpath: req.FullPath,
//		//	},
//		//}
//		rand.Seed(time.Now().UnixNano())
//		t := rand.Intn(10000)
//		ts := strconv.FormatInt(time.Now().UnixMicro(), 10)
//		msgId := "msg" + ts + strconv.Itoa(t)
//		req := &models.ReqWxNotice{
//			Status:       StatusCode,
//			OpenId:       req.OpenId,
//			OrderId:      req.OrderId,
//			AppId:        "wx20a0569be221aa8c",
//			MsgId:        msgId,
//			BusinessId:   150,
//			BusinessInfo: *bi,
//		}
//
//		res, err := helper.PostJson("https://api.weixin.qq.com/cityservice/sendchannelmsg?access_token="+token, req)
//		middlewares.Logger.Println(string(res))
//		middlewares.Logger.Println(err)
//		if err != nil {
//			return err
//		}
//		return nil
//	}
//	return fmt.Errorf("token为空，请更新")
//}
